// import { post, deleter } from '@/api/http'
import { CResponse, request, ResponseCode } from '@/api/request'
import { USER_LIST, USER_DELETE } from '@/api/user'
import {
  usePagination,
  useRowKey,
  useRowSelection,
  useTable,
  useTableColumn,
  useTableHeight,
} from '@/hooks/table'
import { Message, Modal } from '@arco-design/web-vue'
import type { User } from '@/api/type'
import { dateFormat, LONG_TIME } from '@/utils/format'
import { UserState } from '@/store/types'

export enum FlowType {
  Input = 1
}

export const users = ref<UserState[]>([])

export const useUser = () => {

  const table = useTable()
  const pagination = usePagination(doRefresh)
  const visible = ref(false)

  const selectUser = ref<User>()

  const tableColumns = useTableColumn([
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: 'userId',
      dataIndex: 'userId',
    },
    {
      title: '用户名',
      dataIndex: 'userName',
    },
    {
      title: '登录时间',
      dataIndex: 'lastLoginTime',
      render: ({ record }) => dateFormat(LONG_TIME).format(new Date(record.lastLoginTime))
    },
    {
      title: '角色',
      dataIndex: 'userRole',
      slotName: 'userRole',
    },
    {
      title: '操作',
      dataIndex: 'actions',
      slotName: 'actions',
    },
  ])

  const getUserList = async (searchParams?: any) => await request.Post<CResponse>(USER_LIST, searchParams).then(res => res.json())

  async function doRefresh() {
    const res = await getUserList(pagination)
    console.log('user list', res)
    table.handleSuccess(res)
  }

  function onEditItem(item: User) {
    selectUser.value = item
    visible.value = !visible.value
  }

  function onDeleteItem(item: User) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除此数据吗？',
      cancelText: '取消',
      okText: '删除',
      onOk: async () => {
        const { code } = await request.Delete<CResponse>(USER_DELETE + item.id).then(res => res.json())
        if (code === ResponseCode.SUCCESS) {
          Message.success('数据删除成功')
          table.dataList.splice(table.dataList.indexOf(item), 1)
        }
      },
    })
  }

  function addItem() {
    visible.value = !visible.value
  }

  onMounted(async () => {
    table.tableHeight.value = await useTableHeight(getCurrentInstance())
    doRefresh()
  })


  return {
    users,
    table,
    addItem,
    visible,
    doRefresh,
    pagination,
    selectUser,
    getUserList,
    tableColumns,
    onEditItem,
    onDeleteItem,
  }
}
